import {createMemoryHistory, createRouter} from 'vue-router';
import store from "../store/index.js";
import Dashboard from '../views/Dashboard.vue';
import Login from '../views/Login.vue';
import OrderManagement from '../views/OrderManagement.vue';
import LockerManagement from '../views/LockerManagement.vue';
import RoleManagement from '../views/RoleManagement.vue';
import SystemMonitor from '../views/SystemMonitor.vue';

const routes = [
    {
        path: '/',
        name: 'Dashboard',
        component: Dashboard,
        meta: {requiresAuth: true}
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/admin/order',
        name: 'OrderManagement',
        component: OrderManagement,
        meta: {requiresAuth: true}
    },
    {
        path: '/admin/locker',
        name: 'LockerManagement',
        component: LockerManagement,
        meta: {requiresAuth: true}
    },
    {
        path: '/admin/role',
        name: 'RoleManagement',
        component: RoleManagement,
        meta: {requiresAuth: true}
    },
    {
        path: '/admin/monitor',
        name: 'SystemMonitor',
        component: SystemMonitor,
        meta: {requiresAuth: true}
    }
];

const router = createRouter({
    history: createMemoryHistory(),
    routes,
});

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('authToken');
    const isLoggedIn = !!token; // 检查 localStorage 中是否有 token
    const userRole = store.state.user.userRole;

    if (to.meta.requiresAuth && !isLoggedIn) {
        next('/login');
    } else if (to.meta.roles && !to.meta.roles.includes(userRole)) {
        next('/dashboard');
    } else {
        next();
    }
});

export default router;



